require "digest/sha1"
class User < ActiveRecord::Base
  
  has_one :profile
  has_one :active_users, :conditions=>"user_id!=0"
  
  has_many :log,:class_name=>"sb_log"
  has_many :pictures
  has_many :friends
  has_many :incumbents
  has_many :reports
  has_many :companies
  has_many :comments
  has_many :topics
  has_many :inbox_messages, :class_name=>"Message", :foreign_key => "mgser_id" #Receive, inbox
  has_many :outbox_messages, :class_name=>"Message", :foreign_key => "user_id"  #Send, outbox
  
  belongs_to :user_group, :class_name=>"UserGroup"
  
  attr_accessor :password_confirmation
  attr_accessible :name, :password, :password_confirmation, :email, :image_url, :create_ip, :search_tag
  
  def report_age(year)
    return year-profile.birthday.year
  rescue
    return 0
  end
  
  def report_experience(year)
    return year-profile.experience.to_i
  rescue
    return 0
  end
  
  def report_sex
    return profile.sex
  end
  
  def report_education
    return profile.report_education
  end
  
  def tag_list
    return Index.show_tag_list(self)
  end
  
  def report_oversea
    return profile.report_oversea
  end
  
  def before_create
    self.anonymous=0
    self.picture_id=1
    self.deleted=0
    self.password = User.hash_password(self.password)
    self.created_at=Time.now
    self.banned_to=Time.now
    self.search_tag<<" "  unless self.search_tag==""
    self.create_search_tag
  end
  
  def after_create
    Index.index_search_tag(self)
  end
  
  def reindex_search_tag
    self.search_tag<<" "  unless self.search_tag==""
    self.create_search_tag
    Index.clear_search_tag(self)
    Index.index_search_tag(self)
  end
  
  def create_query_conditions(query,category_id,additional_conditions="")
    Keyword.create_query_conditions(query,self,category_id,additional_conditions)
  end
  
  def create_company(params)
    new_company=Company.new(params)
    new_company.user=self
    new_company.save
    return new_company
  end
  
  def create_incumbent(params,company)
    new_incumbent=Incumbent.new(params)
    new_incumbent.view_company=company
    new_incumbent.incumbent_evaluation=IncumbentEvaluation.new
    new_incumbent.user=self
    new_incumbent.created_ip=self.login_ip
    new_incumbent.updated_ip=self.login_ip
    new_incumbent.save
    return new_incumbent
  end
  
  def create_topic(params,forum)
    new_topic=Topic.new(params)
    new_topic.user_id= self.id
    new_topic.forum_id = forum.id
    if new_topic.save
      forum.add_topic(new_topic)
    end
    return new_topic
  end
  
  def create_picture(params,obj_id)
    unless self.guest?
      new_picture = Picture.new(params)
      new_picture.uploader = self  
      obj_id==0 ? new_picture.user=self : new_picture.company=Company.find(obj_id)
      if new_picture.save
        return new_picture
      else
        return false
      end
    else
      return false
    end
  rescue
    return false
  end
  
  def delete_picture(id)
    picture = Picture.find_by_id(id)
    if self.id==picture.user_id and not self.guest?
      picture.destroy
      return true
    else
      return false
    end
  end
  
  def update_topic(params,topic)
    if self.id==topic.user_id
      topic.body=params[:body]
      topic.title=params[:title]
      topic.updated_at= Time.now
      topic.reindex_search_tag
      if topic.save && forum=Forum.find(topic.forum_id)
        forum.update_forum(self)
      end
    end
    return topic
  end
  
  def create_comment(params,obj,user_ip)
    new_comment=Comment.new(params)
    new_comment.created_at= Time.now
    new_comment.created_ip= user_ip
    new_comment.user_id= self.id
    new_comment.obj_id = obj.id
    new_comment.category = Category.find_category(obj)
    if new_comment.save
      obj.reply_times += 1 
      obj.updated_at = Time.now
      obj.save
    end
    return new_comment
  end
  
  def update_comment(params,comment)
    if self.id==comment.user_id
      comment.body=params[:body]
      comment.title=params[:title]
      comment.save
    end
    return comment
  end
  
  def self.validate_params(params)
    validation=[]
    validation<<["<li>用户名已经存在了</li>"] if find_by_name(params[:name])
    validation<<["<li>请输入有效的用户名</li>"] unless params[:name]=~/[\d\w]+/&&params[:name].length<20
    validation<<["<li>设置的密码太短</li>"] if params[:password].length<6
    validation<<["<li>确认的密码不正确</li>"] unless params[:password]==params[:password_confirmation]
    validation<<["<li>邮件地址不正确</li>"] unless params[:email]=~/.+@.+\.(com|net|org)/
    return validation
  end
  
  def after_login_success(activeuser)
    self.login_at=Time.now
    self.login_ip=activeuser.active_user_ip
    self.save
    activeuser.user=self
    activeuser.save
  end
  
  def try_to_login
    User.login(self.name, self.password)
  end
  
  def logout
    self.ol_time=(Time.now - self.login_at).second
    self.save
  end
  
  def banned?
    Time.now<self.banned_to ? true : false
  end
  
  def guest?
    return self.id == GUEST_USER_ID
  end
  
  def adminstrative?
    self.administrative==1 ? true : false
  end
  
  def set_password(pw)
    self.password=User.hash_password(pw || "")
    self.save
  end
  
  def validate_password(old_pw,new_pw,confirm_pw)
    if self.password==User.hash_password(old_pw || "")
      if new_pw==confirm_pw
        if new_pw.length>5
          return nil
        else
          return "新密码太短，更新失败"
        end
      else
        return "两次输入的密码不符"
      end
    else
      return "密码错误，更新失败"
    end
  end
  
  def is_friend(user_id)
    unless Friend.find_by_owner_id_and_friend_id(user_id,self.id)==nil
      return true
    else
      return false
    end 
  end
  
  def log_action(control_name,action_name,obj_id)
    unless self.guest?
      self.pages_view_times+=1
      SbLog.create_log(self,control_name,action_name,obj_id)
      self.save
    end
  end
  
  def self.login(name, password)
    password = hash_password(password || "")
    find(:first,
         :conditions => ["deleted=0 and name = ? and password = ?", 
    name, password])
  end
  
  def create_search_tag
    self.search_tag << self.name
  end
  private
  def self.hash_password(password)
    Digest::SHA1.hexdigest(password)
  end
end
